package com.myBlog.controller;

import com.alibaba.fastjson2.JSONObject;
import com.myBlog.enums.Const;
import com.myBlog.utils.JwtUtil;
import com.myBlog.enums.LoginMsgCode;
import com.myBlog.services.login.CookieLoginService;
import com.myBlog.services.login.JWTLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private CookieLoginService loginService;


    @PostMapping("/login")
    public Map<String,Object> userLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody JSONObject params) {
        HashMap<String, Object> result = new HashMap<>();
        String username = (String) params.get("username");
        String passwd = (String) params.get("password");
        if( !StringUtils.isEmpty(username) && !StringUtils.isEmpty(passwd) ){
            if( loginService.login(username, passwd) ){
                HttpSession session = request.getSession();
                // 将登录用户信息保存到session中
                session.setAttribute( Const.SYSTEM_USER_SESSION.getValue(), username);

                // 设置cookie
                Cookie cookie = new Cookie( Const.SYSTEM_USER_COOkie.getValue(), username);
                // 设置cookie的持久化时间，1天
                cookie.setMaxAge(24*60*60);
                // 设置为当前项目下都携带这个cookie
                cookie.setPath("/");
                // 向客户端发送cookie
                response.addCookie(cookie);

                // 添加请求头的token，防止CSRF攻击
                try {
                    result.put( Const.USER_TOKEN.getValue(), DigestUtils.md5DigestAsHex(username.getBytes("utf-8")).toUpperCase());
                } catch (UnsupportedEncodingException e) {
                    log.error("不支持utf-8格式编码",e);
                    throw new RuntimeException(e);
                }

                result.put("status", LoginMsgCode.Success.getStatus());
                result.put("successInfo", LoginMsgCode.Success.getText());
            }else {
                result.put("status",LoginMsgCode.LoginError.getStatus());
                result.put("errorInfo",LoginMsgCode.LoginError.getText());
            }

        }else {
            result.put("status",LoginMsgCode.LoginNull.getStatus());
            result.put("errorInfo",LoginMsgCode.LoginNull.getText());
        }

        return  result;
    }

    /**
     * 退出登录
     */
    @PostMapping(value = "/logout")
    public Map<String,Object> logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> result = new HashMap<>();
        // 删除session里面的用户信息
        session.removeAttribute( Const.SYSTEM_USER_SESSION.getValue() );
        // 保存cookie，实现自动登录
        Cookie cookie_username = new Cookie(Const.SYSTEM_USER_COOkie.getValue(), "");
        // 设置cookie的持久化时间，0
        cookie_username.setMaxAge(0);
        // 设置为当前项目下都携带这个cookie
        cookie_username.setPath("/");
        // 向客户端发送cookie
        response.addCookie(cookie_username);

        result.put("status",1);
        result.put("successInfo","注销登录成功");
        return result;
    }


    /**
     * 用户登录: JWT登录, 因为jwt退出登录相对麻烦，因此暂时关闭此接口
     * @param request 登录请求
     * @return 响应信息
     */
    @Autowired
    JWTLoginService jwtLoginService;

    //@RequestMapping(value = "/user/jwtLogin")
    public Map<String, Object> jwtLogin(HttpServletRequest request, HttpServletResponse response)  throws IOException {
        // 转为 json
        Map<String, Object> map = new HashMap<>(4);

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        // 验证账号密码是否正确
        String token = jwtLoginService.doLogin(userName, password);
        if( !StringUtils.isEmpty(userName) && !StringUtils.isEmpty(password) && !StringUtils.isEmpty(token)){
            // 登录成功,加上 token
            map.put("loginResult", true);
            map.put("msg", "登录成功");
            map.put("user",userName);
            map.put("token", token);
            response.setHeader(JwtUtil.USER_LOGIN_TOKEN, token);
            return map;
        }else {
            // 登录失败
            map.put("loginResult", false);
            map.put("msg", "登录失败，请认真检查账号密码哦");
        }

        return map;
    }


    @RequestMapping("/currentUser")
    public Map getCurrentUser(HttpServletRequest request,HttpServletResponse response){
        // @todo 这里得的data应该来自session里面的用户区， 只有一个用户，所以就免了。
        HashMap<String, Object> data = new HashMap<>();
        HashMap<Object, Object> result = new HashMap<>();
        String username = "";
        if(request.getCookies()!=null) {
            for (Cookie item : request.getCookies()) {
                if (Const.SYSTEM_USER_COOkie.getValue().equals(item.getName())) {
                    username = item.getValue();
                    break;
                }
            }
        }

        result.put("success",true);
        if(StringUtils.isEmpty(username)){
            response.setStatus(401);

            data.put("isLogin",false);
            result.put("data",data);
            result.put("errorCode",401);
            result.put("errorMessage","请先登录！！!");
        }else {
            data.put("name",username);
            data.put("avatar","https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png");

            result.put("data",data);
        }

        return result;
    }
}
